<template>
  <div class="question-container">
    <h1 class="title">答题模块</h1>
    <h1 class="title">{{ sectionName }}</h1>
    <el-row :gutter="20">
      <!-- 问题展示区 -->
      <el-col :span="16">
        <el-card
            v-for="(problem, index) in problems"
            :key="problem.problemId"
            class="problem-card"
            :id="'problem-' + problem.problemId">  <!-- 为每个问题卡片添加唯一的 id -->

        <h3>{{ index + 1 }}. {{ problem.description }}</h3>
        <img v-if="problem.image" :src="problem.image" alt="Problem Image" class="problem-image" />
        <div v-if="problem.choiceList.length">
          <el-radio-group
              v-model="userAnswers[problem.problemId]"
              :disabled="isSubmitted"
              @change="updateAnswer(problem.problemId)"
          >
            <div
                v-for="choice in problem.choiceList"
                :key="choice.id"
                class="choice-item"
            >
              <el-radio :label="choice.choiceChar">
                <span>{{ choice.choiceChar }}. {{ choice.description }}</span>
                <img v-if="choice.image" :src="choice.image" alt="Option Image" class="choice-image" />
              </el-radio>
            </div>
          </el-radio-group>
        </div>
        </el-card>
      </el-col>

      <!-- 答题卡 -->
      <el-col :span="8">
        <div class="answer-card">
          <h3>答题卡</h3>
          <div class="card-grid">
            <el-button
                v-for="(problem, index) in problems"
                :key="problem.problemId"
                type="info"
                :plain="!userAnswers[problem.problemId]"
                @click="scrollToProblem(problem.problemId)"
            >
              {{ index + 1 }}
            </el-button>
          </div>
          <el-button
              type="success"
              size="large"
              block
              @click="submitAnswers"
              :disabled="isSubmitted"
          >
            提交
          </el-button>
          <div v-if="isSubmitted" class="result-summary">
            <h3>成绩：{{ score }}/{{ totalPoints }}</h3>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, reactive, computed } from 'vue';
import { useRoute } from 'vue-router';
import request from "../utils/request";
import { ElMessage } from "element-plus";

const route = useRoute();
const sectionName = ref(''); // 保存章节名称
const problems = ref([]); // 保存问题列表
let userAnswers = reactive({}); // 保存用户答案
const isSubmitted = ref(false); // 提交状态
const score = ref(0); // 分数
const totalPoints = computed(() =>
    problems.value.reduce((sum, p) => sum + p.point, 0)
);

// 方法：加载章节和问题数据
const loadSectionData = async () => {
  const { sectionId, bookId } = route.params;
  if (!sectionId || !bookId) return;

  try {
    const problemData = await request.post('/api/user/problem/problemList', {
      amount: 10,
      bookId: bookId
    });

    problems.value = problemData.data.data || [];
    sectionName.value = `章节 ${sectionId}`; // 设置章节名称（根据需要调整来源）
    console.log(problemData.data);
  } catch (error) {
    console.error('获取章节或问题数据失败:', error);
  }
};

// 初次加载数据
onMounted(() => {
  loadSectionData();
});

// 监听路由参数变化，动态加载数据并重置状态
watch(
    () => route.params,
    () => {
      // 路由变化时清空分数、答案和提交状态
      userAnswers = reactive({}); // 清空用户答案
      isSubmitted.value = false; // 重置提交状态
      score.value = 0; // 重置分数
      loadSectionData(); // 重新加载数据
    }
);

const submitAnswers = () => {
  let correctCount = 0;
  problems.value.forEach((problem) => {
    if (userAnswers[problem.problemId] === problem.answer) {
      correctCount += problem.point;
    }
  });
  score.value = correctCount;
  isSubmitted.value = true;
  ElMessage.success('答案已提交！');
};

// 跳转到指定问题
const scrollToProblem = (problemId) => {
  document.getElementById(`problem-${problemId}`)?.scrollIntoView({
    behavior: 'smooth',
    block: 'start' // 确保问题出现在视口顶部
  });
};

// 更新答案
const updateAnswer = (problemId) => {
  console.log(`Updated answer for Problem ${problemId}:`, userAnswers[problemId]);
};
</script>


<style scoped>
.question-container {
  margin: 20px;
}

/* 问题展示区样式 */
.problem-card {
  border: 1px solid #dcdfe6; /* 添加边框 */
  background-color: #f9fafb; /* 背景色微微灰色 */
  padding: 20px;
  margin-bottom: 20px; /* 问题之间的间隙 */
  border-radius: 8px; /* 圆角 */
}

/* 问题图片样式 */
.problem-image {
  width: 100%;
  height: auto;
  margin-top: 10px;
}

/* 答题卡样式 */
.answer-card {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  position: fixed; /* 使答题卡固定 */
  top: 100px; /* 距离顶部20px */
  right: 20px; /* 距离右侧20px */
  width: 250px; /* 设置宽度 */
  z-index: 10; /* 确保答题卡在上方 */
  max-height: 80vh; /* 最大高度不超过视口高度的80% */
  overflow-y: auto; /* 使答题卡可滚动 */
}

/* 答题卡按钮样式 */
.card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

/* 答题卡按钮样式 */
.el-button {
  margin: 5px;
}
</style>
